import dynamic from 'next/dynamic'
import Layout from '@c/layout'
import Responsive from '@c/responsive'
import VideoPlayer from '@c/video/video-player'
import message from '@c/message'
import Copy from 'clipboard'
import { isPureNumber, isJSONString, getSpaceAndPage } from '@/utils/utils'
import { vodActionExport } from '@/utils/report'
import { useShowLogin, useVipDialog } from '@/utils/hooks'
import styles from './index.module.scss'
import { useEffect, useState, useMemo } from 'react'
import { FILM_URL } from '@/constant'
import { userInfo, cacheLineState, pcStore } from '@/store'
import { useRecoilState, useRecoilValue } from 'recoil'
import { useRouter } from 'next/router'
import omit from 'lodash-es/omit'
import cm from 'classnames'
import LiveLoading from '@c/live-icon'
import Link from 'next/link'
import Button from '@c/button'
import ArrowSvg from '@c/svg/arrow'
import { taskFinished } from '@/api/score'

import {
  getRelatedActor,
  getRecommendInfo,
  getVodCollection,
  getVodCollectionLines,
} from '@/api/vod'
import { getVodHistoryDuration, getVodCollected, vodCancelCollected, vodCollected } from '@/api/history-collect'
import { vodDetailReport, scoreTaskFinishedReport } from '@/utils/report'
import playToast from '@c/play/play-toast'

const PlayJujiPhone = dynamic(() => import('@c/play/play-juji-phone'))
const PlayJujiPc = dynamic(() => import('@c/play/play-juji-pc'))
const DownloadPhone = dynamic(() => import('@c/download/download-phone'))
const DownloadTv = dynamic(() => import('@c/download/download-tv'))
const ActorItem = dynamic(() => import('@c/actor-item'))
const HFilmList = dynamic(() => import('@c/h-film-list'))
//获取当前线路集合

const getLines = (eporder, lines) => {
  const currLine = lines?.find(item => item.eporder == eporder) || {}
  //筛除没有的url
  return (currLine.lines || []).filter(item => item.purl)
}

const getVEId = (ep, arr) => {
  try {
    for (let i = 0; i < arr.length; i++) {
      const currMovie = arr[i].videos?.find(item => item.eporder == ep)
      if (currMovie) {
        return currMovie
      }
    }
  } catch (error) { }
  return {}
}

const Index = props => {
  const { cid, recommend, relateActor, collectionInfo, totalSize, selectionInfo, lineGroup } = props
  const ep = selectionInfo.ep
  const user = useRecoilValue(userInfo)
  const isPc = useRecoilValue(pcStore)
  const router = useRouter()
  const [lineState, updateLineState] = useRecoilState(cacheLineState)
  const { renderLabel, isMovie } = collectionInfo
  const setErrorCode = VideoPlayer.useSetErrorCode(0)
  const openVip = useVipDialog()
  const setShowLogin = useShowLogin()
  const [isCollected, setCollected] = useState(false) //点播是否收藏
  const [openLinePanel, toggleLinePanel] = useState(false)
  const [isInit, setInit] = useState(false)
  const [showThirdToast, setThirdToast] = useState(false)
  const [showToast, setToast] = useState('')
  const [hasHistory, setHistoryLoad] = useState({ code: 0 }) // 0未加载 1没有历史 2 有历史
  const eporderName = useMemo(() => {
    try {
      return ep + '.' + lineGroup.eporder[ep - 1].videoName
    } catch (error) {
      return ''
    }
  }, [lineGroup, ep])
  // 当前播放线路
  const currPlayLines = useMemo(() => {
    return getLines(selectionInfo.ep, lineGroup.eporder)
  }, [selectionInfo.ep, cid])
  // 播放链接
  useEffect(() => {
    // 历史和详情接口没有拿到则退出
    if (!hasHistory.code || typeof user.token == 'undefined') {
      return
    } else if (hasHistory.code == 1) {
      // 无历史记录
      updateLineState(currPlayLines.length ? currPlayLines[0] : lineState)
    } else {
      // 会员但是播放的是非vip,其他的都播放历史记录
      const isVipHistory = user.isVip && !hasHistory.line.isOfficial
      updateLineState(isVipHistory ? currPlayLines[0] : hasHistory.line)
    }
  }, [currPlayLines, hasHistory, user])
  // 当前线路情况

  const lineStatus = useMemo(() => {
    // 无线路
    if (!currPlayLines.length) {
      return {
        empty: true
      }
    }
    //无最优，有普通
    if (currPlayLines.every(item => !item.isOfficial)) {
      return {
        onlyNormal: true
      }
    }
    // 无普通，有最优
    if (currPlayLines.every(item => item.isOfficial)) {
      return {
        onlyOfficial: true
      }
    }
    //有最优，有普通
    if (currPlayLines.some(item => item.isOfficial) && currPlayLines.some(item => !item.isOfficial)) {
      return {
        both: true
      }
    }
  }, [currPlayLines, router.asPath])

  //点播是否已收藏
  const getVodCollect = async token => {
    if (!token) {
      return
    }
    const res = await getVodCollected(cid, token)
    setCollected(res?.data?.isFavorite)
  }
  // 初始化数据。
  useEffect(() => {
    // 获取点播是否收藏
    const token = localStorage.getItem('token')
    getVodCollect(token)
    return () => {
      sessionStorage.setItem('lastPage', true)
    }
  }, [cid])

  //获取播放历史
  useEffect(() => {
    const token = localStorage.getItem('token')
    getVodPlayed(token, user)
  }, [cid, ep])

  // 播放历史剧集信息记录
  useEffect(() => {
    const currMovie = getVEId(ep, collectionInfo.videosGroup)
    window.varReport = {
      mid: currMovie.vid,
      cid: parseInt(cid),
      num: ep,
      eid: currMovie.eid,
      img: collectionInfo.picurl,
      lId: lineState?.lId || 0,
      chName: collectionInfo.chname,
      name: collectionInfo.name
    }
  }, [router.asPath, lineState])

  // 收藏与取消收藏专辑
  const collected = async () => {
    const token = localStorage.getItem('token')
    if (!token) {
      setShowLogin(true)
      return
    }
    vodActionExport({
      channel_name: collectionInfo.name
    })
    let res = null
    if (isCollected) {
      res = await vodCancelCollected(cid, token)
    } else {
      res = await vodCollected(+cid, token)
    }
    if (!res.code) {
      message({ content: isCollected ? '取消收藏成功' : '收藏成功！' })
      setCollected(!isCollected)
    } else {
      message({ content: res.msg })
    }
  }

  // 分享点播
  const urlMemo = useMemo(() => {
    const str = `《${collectionInfo.name}》剧情太精彩了，快来星视界一起看！免费高清观看地址：https://www.histar.tv/vod/detail/${cid}`
    return str
  }, [cid])
  useEffect(() => {
    const copyUrl = new Copy('.share-vod-btn')
    copyUrl.on('success', () => {
      message({ content: '链接复制成功，分享给好友可领积分兑免费会员~' })
      const token = localStorage.getItem('token')
      if (token) {
        taskFinished({
          completionStatus: 2,
          ydtoken: ''
        })
      }
      scoreTaskFinishedReport({
        points_name: '点播分享'
      })
      vodDetailReport({
        share_status: '链接'
      })
    })
  }, [])

  //获取播放进度,设置当前播放线路
  const getVodPlayed = async token => {
    let his = {
      code: 1,
      line: currPlayLines[0]
    }
    if (token) {
      const res = await getVodHistoryDuration({ cid }, token)
      if (res.data) {
        const lId = res?.data?.lId
        const line = currPlayLines.find(item => item.lId == lId)
        if (line) {
          his = {
            code: 2,
            line: line
          }
        }
      }
    } else {
      let vodHistory = JSON.parse(localStorage.getItem('vod-history') || '[]')
      const playedLine = vodHistory.find(item => item.cid == cid)
      if (playedLine) {
        let line = currPlayLines.find(item => item.lId == playedLine.lId)
        if (line) {
          his = {
            code: 2,
            line: line
          }
        }
      }
    }
    setHistoryLoad(his)
    setInit(true)
  }

  // 检查是否是vip用户
  useEffect(() => {
    // 历史记录还未加载，不做处理
    if (!hasHistory.code) {
      return
    }
    if (typeof user.token == 'undefined') {
      return
    }
    // 未登录处理
    if (!localStorage.getItem('token') && (lineStatus.both || lineStatus.onlyOfficial)) {
      // 先拿取本地缓存数据。
      let vodHistory = JSON.parse(localStorage.getItem('vod-history') || '[]')
      const playedLine = vodHistory.find(item => item.cid == cid && item.num == ep)
      if (playedLine && lineStatus.both) {
        openVipDialog()
        return
      }
      if (!lineState.isOfficial) {
        return
      }
      setErrorCode('7')
      return
    }
    // 是vip且只有普通线
    if (user.isVip && lineStatus.onlyNormal) {
      showGuide('onlyNormal', '')
    }
    // 无数据求片
    if (lineStatus.empty) {
      setErrorCode('4')
      return
    }
    // 当前播放是官方线，验证用户是不是vip
    if (user.email) {
      if (lineState.isOfficial) {
        // 有官方线和普通线且非vip才启用错误
        if (!user.isVip && lineStatus.both) {
          setErrorCode('1-1')
          return
        }
        // 只有官方线且非vip才启用错误
        if (!user.isVip && lineStatus.onlyOfficial) {
          setErrorCode('2-1')
          return
        }
      } else {
        // 有播放历史且非vip
        if (!user.isVip && lineStatus.both && hasHistory.code == 2) {
          openVipDialog()
          return
        }
      }
    }
    setErrorCode(0)

    return () => {
      setHistoryLoad({ code: 0 })
    }
  }, [user, lineStatus, router.asPath, lineState, hasHistory])
  // errorCode改变

  //分享上报
  const share = () => {
    const token = localStorage.getItem('token')
    if (token) {
      taskFinished({
        completionStatus: 2,
        ydtoken: ''
      })
    }
    scoreTaskFinishedReport({
      points_name: '点播分享'
    })
    vodDetailReport({
      share_status: '链接'
    })
  }

  useEffect(() => {
    const copyUrl = new Copy('.share-btn')
    copyUrl.on('success', () => {
      message({ content: '链接复制成功，分享给好友可领积分兑免费会员~' })
      share()
    })
    return () => {
      sessionStorage.setItem('lastPage', true)
    }
  }, [])

  const buffered = type => {
    if (!type) {
      return
    }
    showGuide('kadun', '使用客户端播放更流畅')
  }

  const openVipDialog = () => {
    setToast(true)
    setTimeout(() => {
      setToast(false)
    }, 5000)
  }

  const showGuide = (type, content) => {
    if (type == 'not-vip') {
      openVipDialog()
    }
    playToast({
      type,
      content,
      cid,
      ep,
      vEid: getVEId(ep, collectionInfo.videosGroup)
    })
  }

  useEffect(() => {
    // 未获取到用户信息
    if (typeof user.token === 'undefined') {
      return
    }
    // 没有起播
    if (!showThirdToast) {
      return
    }
    setThirdToast(false)
    // 会员且只有普通线路，不展示三方广告提示
    if (user.isVip && lineStatus.onlyNormal) {
      return
    }
    showGuide('normal', '')
  }, [showThirdToast, lineStatus, user])

  //更新播放线路

  const updateCurrLine = (item, index) => {
    let code = 0
    if (item.isOfficial) {
      if (typeof user?.token !== 'undefined' && !user?.token) {
        code = '7'
      } else if (!user.isVip) {
        code = '1-1'
      }
    }
    setErrorCode(code)
    updateLineState({
      ...item,
      index
    })
  }
  //切换线路
  const switchLine = (item, index) => {
    if (!item.isOfficial) {
      updateCurrLine(item, index)
      return
    }
    if (!user.token) {
      setShowLogin()
      return
    }
    if (!user.isVip) {
      openVip()
      return
    }
    updateCurrLine(item, index)
  }
  return (
    <>
      <Responsive className={styles.playContainer} top={80}>
        <div className={cm(styles.playBox, styles.playBoxPhone, 'sticky')}>
          <div className={styles.playArea}>
            <div className={styles.play}>
              <VideoPlayer
                playType="HLS"
                onBufferChange={buffered}
                description={collectionInfo.desc}
                keywords={renderLabel?.join(',')}
                isCollected={isCollected}
                lineArr={currPlayLines}
                onError={() => setErrorCode('3')}
                isMovie={isMovie}
                totalSize={totalSize}
                needP2P={true}
                cid={cid}
                selectionInfo={selectionInfo}
                onLineSwitch={data => showGuide(data.type, data.content)}
                onNormalStart={() => setThirdToast(true)}
                ep={ep}
                from="VOD"
                lineStatus={lineStatus}
                isInit={isInit}
                isShows={collectionInfo.isShows}
                currPlayLines={currPlayLines}
                name={collectionInfo?.name + (isMovie ? '' : `第${ep}集`)}
              />
              <div className={styles.showToast} id="play-toast"></div>

              {showToast && (
                <div className={cm(styles.openVipPanel, 'hideWhenPhone')}>
                  {typeof user?.token !== 'undefined' && !user?.token ? (
                    <p className={styles.dailyPrice}>注册臻享最优播放体验</p>
                  ) : (
                    <p className={styles.dailyPrice}>开通VIP，臻享最优播放体验！</p>
                  )}
                  <p className={styles.good}>清晰 | 流畅 | 多语言 | 无广告</p>
                  {typeof user?.token !== 'undefined' && !user?.token ? (
                    <div className={styles.btn} onClick={setShowLogin}>
                      立即登录
                    </div>
                  ) : (
                    <div className={styles.btn} onClick={() => openVip(1)}>
                      开通VIP
                    </div>
                  )}
                </div>
              )}
              {showToast && (
                <div className={cm(styles.openVipPanelPhone, 'hideWhenPc')}>
                  <img src="/images/vip-juji.png" alt="VIP" />
                  {typeof user?.token !== 'undefined' && !user?.token ? (
                    <span className={styles.btn} onClick={setShowLogin}>
                      开通VIP，甄选最优播放体验{'>>'}
                    </span>
                  ) : (
                    <span className={styles.btn} onClick={() => openVip(1)}>
                      开通VIP，甄选最优播放体验{'>>'}
                    </span>
                  )}
                </div>
              )}
            </div>
            <div className={cm(styles.playMenu, 'hideWhenPhone')}>
              <div className={styles.menuLeft}>
                <div className={cm(styles.btn, isCollected ? styles.btnCollected : '')} onClick={collected}>
                  <img src={'/images/' + (isCollected ? 'collect_active' : 'collect_page') + '.png'} alt="收藏" />
                  {isCollected ? '已' : ''}收藏
                </div>
                <div className={cm(styles.btn, styles.btnShare, 'share-vod-btn')} data-clipboard-text={urlMemo}>
                  <img src="/images/share.png" alt="分享" />
                  分享
                  <img src="/images/corn.webp" alt="corn" className={styles.corn} />
                </div>
                <div className={cm(styles.btn, styles.btnDownload)} onClick={() => router.push('/download')}>
                  <img src="/images/download.png" alt="收藏" />
                  下载
                  <span className={styles.corner}>客户端专享</span>
                </div>
              </div>
              <div className={styles.menuRight}>
                <div className={cm(styles.btn, styles.btnRight)} onClick={() => router.push('/download?to=phone')}>
                  <img src="/images/collect_page.png" alt="收藏" />
                  手机随时看
                  <DownloadPhone className={styles.btnHover} />
                </div>
                <div className={cm(styles.btn, styles.btnRight)} onClick={() => router.push('/download?to=tv')}>
                  <img src="/images/tv-download.png" alt="收藏" style={{ width: 20 }} />
                  TV大屏观看
                  <DownloadTv className={styles.btnHover} />
                </div>
              </div>
            </div>
          </div>
          <div className={cm(styles.sectionBox, 'hideWhenPhone')}>
            <h1 className={cm(styles.vodName, 'textEllipsis')}>{collectionInfo.name}</h1>
            <div className={styles.lines}>
              {currPlayLines.length ? (
                currPlayLines?.slice(0, 2).map((item, index) => {
                  return (
                    <div
                      key={index}
                      className={cm({
                        [styles.lineBtn]: true,
                        [styles.lineLive]: !item.isOfficial && (lineState.lId === item.lId || lineState.index == index),
                        [styles.lineOfficial]: item.isOfficial,
                        [styles.lineThird]: !item.isOfficial
                      })}
                      onClick={() => switchLine(item, index)}
                    >
                      {(lineState.lId === item.lId || lineState.index == index) && (
                        <LiveLoading type={item.isOfficial ? 'vod' : 'default'} style={{ marginLeft: 0 }} />
                      )}
                      <span>{item.name}</span>
                      {item.isOfficial && (
                        <div className={styles.vipTip}>
                          <span>{user.token ? '超清流畅无广告' : '登录领会员畅享'}</span>
                        </div>
                      )}
                    </div>
                  )
                })
              ) : (
                <div className={styles.noLine}>暂无可播放线路～</div>
              )}
              {currPlayLines.length > 1 && (
                <div
                  className={cm(
                    styles.lineBtn,
                    styles.lineThird,
                    styles.switchLine,
                    openLinePanel ? styles.openPanel : ''
                  )}
                  onClick={() => toggleLinePanel(!openLinePanel)}
                >
                  <img src="/images/arrow.webp" className={styles.arrow} alt="箭头" />
                </div>
              )}

              {openLinePanel && (
                <div className={styles.linePanel}>
                  {currPlayLines.length > 2 ? (
                    currPlayLines.map((item, index) => {
                      return (
                        <div
                          key={index}
                          className={cm({
                            [styles.lineBtn]: true,
                            [styles.lineLive]:
                              !item.isOfficial && (lineState.lId === item.lId || lineState.index == index),
                            [styles.lineOfficial]: item.isOfficial,
                            [styles.lineThird]: !item.isOfficial,
                            [styles.linePanelItem]: true
                          })}
                          onClick={() => switchLine(item, index)}
                        >
                          <span>{item.name}</span>
                          {(lineState.lId === item.lId || lineState.index == index) && (
                            <LiveLoading type={item.isOfficial ? 'vod' : 'default'} />
                          )}
                        </div>
                      )
                    })
                  ) : (
                    <div className={styles.nullLine}>
                      <img src="/images/null.png" alt="无数据" className={styles.img} />
                      <p className={styles.text}>暂无更多播放线路~</p>
                    </div>
                  )}
                </div>
              )}
            </div>
            {/* 非电影模块DOM */}
            {!collectionInfo.isMovie && (
              <PlayJujiPc collectionInfo={collectionInfo} lineGroup={lineGroup} selectionInfo={selectionInfo} />
            )}
            {/* 电影介绍存在DOM */}
            {collectionInfo.isMovie && (
              <div className={cm(styles.movieList, 'hideWhenPhone')}>
                <h2 className={styles.listTitle}>相关推荐</h2>
                {recommend.cards?.map(item => {
                  return (
                    <Link href={`/vod/play-official/${item.id}/1`} replace className={styles.listItem} key={item.id}>
                      <img src={item.img} alt={item.name} className={styles.img} />
                      <div className={cm(styles.listName, 'textEllipsis')}>{item.name}</div>
                    </Link>
                  )
                })}
              </div>
            )}
          </div>
        </div>
      </Responsive>
      <Layout>
        <section className={cm(styles.detailPhone, 'hideWhenPc')}>
          <h1 className={styles.title}>
            <span>{collectionInfo.name}</span>
            {!isMovie && (
              <>
                <ArrowSvg className={styles.arrow} width={16} />
                <span className={styles.eporderName}>{eporderName}</span>
              </>
            )}
          </h1>
          <div className={styles.score2menu}>
            <div>
              <p className={styles.infoVod}>
                {collectionInfo.time && <span>{collectionInfo.time}</span>}
                {collectionInfo.countStr && <span>&nbsp;|&nbsp;{collectionInfo?.countStr?.split('/')[0]}</span>}
              </p>
              <div className={styles.scoreBox}>
                {collectionInfo.tmdbScore ? (
                  <div className={styles.mark}>
                    <img loading="lazy" src="/images/tmdb.png" alt="tmdb" className={styles.tmdb} />
                    <span className={styles.tmdbText}>{('' + collectionInfo.tmdbScore).toFix(1)}</span>
                  </div>
                ) : null}
                {collectionInfo.doubanScore ? (
                  <div className={styles.mark}>
                    <img loading="lazy" src="/images/douban.png" alt="douban" className={styles.douban} />
                    <span className={styles.doubanText}>{('' + collectionInfo.doubanScore).toFix(1)}</span>
                  </div>
                ) : null}
              </div>
            </div>
            <div className={styles.detailMenuGroup}>
              <Button className={cm(styles.btn)} onClick={collected}>
                <img src={'/images/' + (isCollected ? 'collect_active' : 'collect_page') + '.png'} alt="收藏" />
              </Button>
              <Button
                className={cm(styles.btn, styles.share, 'share-btn')}
                data-clipboard-text={`《${collectionInfo.name}》剧情太精彩了，快来星视界一起看！免费高清观看地址：https://www.histar.tv/vod/detail/${cid}`}
              >
                <img loading="lazy" src="/images/share.png" alt="分享" />
                <img loading="lazy" src="/images/corn.webp" alt="corn" className={styles.corn} />
              </Button>
              <Button onClick={() => router.push('/download')} className={cm(styles.btn, styles.download)}>
                <img loading="lazy" src="/images/download.png" alt="下载" />
              </Button>
            </div>
          </div>
          <div className={styles.tag}>
            {collectionInfo.renderLabel.length
              ? collectionInfo?.renderLabel?.map((item, index) => {
                return (
                  <div key={index} className={styles.item}>
                    {item}
                  </div>
                )
              })
              : '暂无分类信息'}
          </div>
          <div className={cm(styles.linesH5, 'scrollBeautify')}>
            {currPlayLines.length ? (
              currPlayLines.map((item, index) => {
                return (
                  <div
                    key={index}
                    className={cm({
                      [styles.lineBtn]: true,
                      [styles.lineLive]: !item.isOfficial && (lineState.lId === item.lId || lineState.index == index),
                      [styles.lineOfficial]: item.isOfficial,
                      [styles.lineThird]: !item.isOfficial
                    })}
                    onClick={() => switchLine(item, index)}
                  >
                    {(lineState.lId === item.lId || lineState.index == index) && (
                      <LiveLoading type={item.isOfficial ? 'vod' : 'default'} style={{ marginLeft: 0 }} />
                    )}
                    <span>{item.name}</span>
                    {/* {item.isOfficial && (
                        <div className={styles.vipTip}>
                          <span>{user.token ? '超清流畅无广告' : '登录领会员畅享'}</span>
                        </div>
                      )} */}
                  </div>
                )
              })
            ) : (
              <div className={styles.noLine}>暂无可播放线路～</div>
            )}
          </div>
          <div className={styles.my}></div>
          {/* 非电影模块DOM */}
          {!collectionInfo.isMovie && (
            <PlayJujiPhone collectionInfo={collectionInfo} lineGroup={lineGroup} selectionInfo={selectionInfo} />
          )}
        </section>
        {relateActor && relateActor.length && <ActorItem list={relateActor} />}
        {isMovie && isPc ? null : <HFilmList data={recommend} fontSize={24} source={FILM_URL[collectionInfo.chname]} top={48} />}
      </Layout>
    </>
  )
}

export default Index

// 组装详情数据
const generateCollectionData = general => {
  const data = {
    ...omit(general, ['label']),
    renderLabel: [],
    isMovie: general.chname === '电影',
    isShows: general.chname === '综艺',
    imgUrl: general.picurl || '/images/default.png',
    posterUrl: general.posterUrl || general.picurl || '/images/horizon'
  }

  // 导演和演员处理
  data.actor = isJSONString(general.actor) ? JSON.parse(general.actor).join(' / ') : data.actor
  data.actor = isJSONString(general.director) ? JSON.parse(general.director).join(' / ') : data.director
  // 处理标签
  data.renderLabel = [data.chname, ...general.label?.split(' / ')].filter(item => item)
  return data
}


const formatDesc = (lineGroup, collectionInfo, ep) => {
  if (collectionInfo.isMovie) {
    let desc = `在线观看${collectionInfo.name}，影片讲述了${collectionInfo.desc}`
    if (desc.length > 120) {
      desc = desc.slice(0, 120) + '...'
    }
    return desc
  }
  let desc = `在线观看${collectionInfo.name}`
  const epDesc = lineGroup.eporder?.find(item => item.eporder == ep)?.overView
  if (epDesc) {
    desc += `，该集讲述了${epDesc}`
  }
  if (desc.length > 120) {
    desc = desc.slice(0, 120) + '...'
  }
  return desc
}
export async function getServerSideProps({ params }) {
  const { ep, id: cid } = params
  // 输出404页面
  if (!isPureNumber(ep) || !isPureNumber(cid)) return { notFound: true }

  // 处理分页数据
  const pagesInfo = await getVodCollectionLines({ cid, page: 1, pageSize: 1, sort: 1 })
  const selectionInfo = getSpaceAndPage(ep, pagesInfo.data?.total || 0, true)

  const resArr = (
    await Promise.allSettled([
      getVodCollection(cid, {}),
      getRecommendInfo(cid, {}),
      getRelatedActor(cid, {}),
      getVodCollectionLines({ cid, page: selectionInfo.pageNo, pageSize: selectionInfo.pageSize, sort: 1 })
    ])
  )
    .map(item => item.value)
    .map(item => {
      if (item.code === 0) {
        return {
          data: item.data
        }
      }
      return {
        data: {}
      }
    })
  // cid不存在，输出404
  try {
    if (!resArr[0].data?.id) {
      return { notFound: true }
    }
  } catch (error) {
    return { notFound: true }
  }

  const collectionInfo = generateCollectionData(resArr?.[0]?.data || {})
  let layoutProps = {}
  const lineGroup = resArr[3].data
  // 处理布局props
  try {
    layoutProps = {
      noSomeMetaInfo: false,
      title: `${collectionInfo.name}${collectionInfo.eptotal && collectionInfo.isMovie ? '' : `第${ep}集`
        } - 在线观看 - 星视界`,
      desc: formatDesc(lineGroup, collectionInfo, ep),
      url: FILM_URL[collectionInfo.chname] || ''
    }
  } catch (error) { }
  return {
    props: {
      isThird: false,
      ep: parseInt(ep),
      cid,
      selectionInfo,
      totalSize: pagesInfo?.data?.total || 0,
      collectionInfo,
      recommend: {
        name: '相关推荐',
        ban: true,
        cards: resArr[1]?.data?.cards || []
      },
      relateActor: resArr[2].data?.actors || [],
      layoutProps,
      lineGroup
    }
  }
}
